package com.hooya.fa.eu.biz.dao.manager.special;

import com.hooya.fa.eu.api.bo.stk.BuyRecordBO;
import com.hooya.fa.eu.api.enums.CkEnum;
import com.hooya.fa.eu.api.enums.CompanyEnum;
import com.hooya.fa.eu.api.enums.CountryEnum;
import com.hooya.fa.eu.biz.dao.entity.PlaceMatchDict;
import com.hooya.fa.eu.biz.dao.entity.TempJcjl;
import com.hooya.fa.eu.biz.dao.entity.TempKcjlDaily;
import com.hooya.fa.eu.biz.dao.entity.TradeRecord;
import com.hooya.fa.eu.biz.dao.manager.GeneratorEntityManager;
import com.hooya.integrated.common.core.util.RedisUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import static com.hooya.fa.eu.api.constant.DictConstant.DICT_PREFIX;

/**
 * @Description 1
 * @Author : Zongz
 * @Copyright Copyright (c) 豪雅集团
 * @Create 2024/2/27
 * @Version 1.0.0
 */
@Slf4j
@Component
@AllArgsConstructor
public class JcDataManager {

    private final GeneratorEntityManager entityManager;

    /**
     * 处理原始数据
     *
     * @param df                日期格式工具
     * @param warehousingList   原始进仓数据
     * @param recordList        处理后的进仓数据集合
     * @param placeMatchDictMap place匹配字典
     */
    public void dealSourceJcData(SimpleDateFormat df, List<BuyRecordBO> warehousingList, List<BuyRecordBO> recordList,
                                 Map<String, PlaceMatchDict> placeMatchDictMap) {
        Map<String, String> abnormalBelongsMap =
                RedisUtils.hmget(DICT_PREFIX + CkEnum.ABNORMAL_BELONGS_MAP.getName());
        warehousingList.forEach(l -> {
            try {
                Date htrqDate = df.parse(l.getHtrq());
                if (StringUtils.isNotBlank(abnormalBelongsMap.get(l.getHthm())) && StringUtils.isBlank(l.getBelongs())) {
                    l.setBelongs(abnormalBelongsMap.get(l.getHthm()));
                }
                if (htrqDate.compareTo(df.parse("2019-08-28")) <= 0) {
                    l.setBelongs("FDS-DE");
                }
            } catch (Exception e) {
                throw new RuntimeException("时间格式化失败！htrq：" + l.getHtrq());
            }
            //货权没有的话，移除数据
            if (StringUtils.isBlank(l.getBelongs()) || StringUtils.isBlank(l.getCpbh()) || l.getPlace().equals("EU07")) {
                return;
            }
            PlaceMatchDict p = placeMatchDictMap.get(l.getPlace());
            //仓库地址对应的是restock的话，移除数据
            if (Objects.nonNull(p)) {
                if (p.getType().equals("restock") || p.getRealWhId().equals("EU07")) {
                    log.info("进仓为【" + p.getRealWhId() + "】");
                    return;
                }
                l.setPlace(p.getRealWhId());
            }
            recordList.add(l);
        });
    }

    /**
     * 处理进仓数据，转变为买卖数据
     *
     * @param jcData           进仓数据
     * @param inventoryList    仓库数据
     * @param tradeRecordList  买卖记录
     * @param tempJcjlList     进仓记录
     * @param metaWarehouseMap 仓库国家字典
     */
    public void dealJcDataTurnTempData(List<BuyRecordBO> jcData, List<TempKcjlDaily> inventoryList,
                                       List<TradeRecord> tradeRecordList, List<TempJcjl> tempJcjlList,
                                       Map<String, String> metaWarehouseMap) {
        if (!CollectionUtils.isEmpty(jcData)) {
            for (BuyRecordBO jc : jcData) {
                String realBelongs = jc.getBelongs().toLowerCase();
                String fromCompany = "";
                String fromCountry = "";
                String origin = metaWarehouseMap.get(jc.getPlace());
                if (jc.getBelongs().contains("FDS")) {
                    if (origin.equals(CountryEnum.DE.getCountry())) {
                        realBelongs = CompanyEnum.FDS_DE.getCompany();
                    } else {
                        realBelongs = "fds-" + origin.toLowerCase();
                        fromCompany = CompanyEnum.FDS_DE.getCompany();
                        fromCountry = CountryEnum.DE.getCountry();
                    }
                }
                if (jc.getBelongs().equals(CompanyEnum.COSTWAY_PL.getCompany().toUpperCase())) {
                    if (!origin.equals(CountryEnum.PL.getCountry())) {
                        realBelongs = "costway-" + origin.toLowerCase();
                        fromCompany = CompanyEnum.COSTWAY_PL.getCompany();
                        fromCountry = CountryEnum.PL.getCountry();
                    }
                }
                if (jc.getBelongs().equals(CompanyEnum.COSTWAY_FR.getCompany().toUpperCase())) {
                    if (!origin.equals(CountryEnum.FR.getCountry())) {
                        realBelongs = "costway-" + origin.toLowerCase();
                        fromCompany = CompanyEnum.COSTWAY_FR.getCompany();
                        fromCountry = CountryEnum.FR.getCountry();
                    }
                }
                if (jc.getBelongs().equals(CompanyEnum.COSTWAY_DE.getCompany().toUpperCase())) {
                    if (!origin.equals(CountryEnum.DE.getCountry())) {
                        realBelongs = "costway-" + origin.toLowerCase();
                        fromCompany = CompanyEnum.COSTWAY_DE.getCompany();
                        fromCountry = CountryEnum.DE.getCountry();
                    }
                }
                if (StringUtils.isNotBlank(realBelongs) && StringUtils.isNotBlank(fromCompany) &&
                        StringUtils.isNotBlank(fromCountry)) {
                    tradeRecordList.add(entityManager.genTradeRecord(jc, jc.getCgsl(), fromCompany,
                            realBelongs, fromCountry, origin, "海运"));
                }
                //jc与kc的belongs大写
                String finalRealBelongs = realBelongs.toUpperCase();
                if (inventoryList.stream().anyMatch(l ->
                        l.getCpbh().equals(jc.getCpbh()) && l.getPlace().equals(jc.getPlace()) &&
                                finalRealBelongs.equals(l.getBelongs()))) {
                    inventoryList.stream().filter(l ->
                                    l.getCpbh().equals(jc.getCpbh()) && l.getPlace().equals(jc.getPlace()) &&
                                            finalRealBelongs.equals(l.getBelongs()))
                            .forEach(l -> l.setSl(l.getSl() + jc.getCgsl()));
                } else {
                    inventoryList.add(
                            entityManager.genTempKcjlDaily(jc.getCpbh(), finalRealBelongs, jc.getPlace(),
                                    jc.getCgsl(), jc.getHtrq()));
                }
                tempJcjlList.add(entityManager.genTempJcjl(jc, finalRealBelongs));
            }
        }
    }

    public List<BuyRecordBO> getCurMonthJcData(SimpleDateFormat df, String startDate, String endDate,
                                               List<BuyRecordBO> recordList) {
        return recordList.stream().filter(l -> {
            try {
                long dateTime = df.parse(l.getHtrq()).getTime();
                if (dateTime >= df.parse(startDate).getTime() &&
                        dateTime < df.parse(endDate).getTime()) {
                    return true;
                }
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage() + ",时间格式化失败！htrq：" + l.getHtrq());
            }
            return false;
        }).collect(Collectors.toList());
    }
}
